package com.jhj.common.redis.impl;

import com.jhj.common.redis.JhjRedis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * 金惠家redis缓存访问接口实现类
 * 
 * @author GaoXiang Date: 2014-7-21
 */
public class JhjRedisImpl implements JhjRedis {
    
    /**
     * 金惠家缓存对象统一前缀
     */
    private static final String JHJ_REDIS_KEY_PREFIX = "jhj_";
    
    /**
     * redis访问对象
     */
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    /**
     * 放入缓存
     * 
     * @param key
     * @param o
     * @param expire 过期时间，单位：秒
     */
    @Override
    public void put(String key, Object o, int expire) {
        redisTemplate.opsForValue().set(JHJ_REDIS_KEY_PREFIX + key, o);
        redisTemplate.expire(JHJ_REDIS_KEY_PREFIX + key, expire, TimeUnit.SECONDS);
    }
    
    /**
     * 从缓存删除
     * 
     * @param key
     */
    @Override
    public void delete(String key) {
        redisTemplate.delete(JHJ_REDIS_KEY_PREFIX + key);
    }
    
    /**
     * 从缓存取出数据
     * 
     * @param key
     * @return
     */
    @Override
    public Object get(String key) {
        return redisTemplate.opsForValue().get(JHJ_REDIS_KEY_PREFIX + key);
    }

    @Override
    public long incr(String key, int expire) {
        long num = redisTemplate.opsForValue().increment(JHJ_REDIS_KEY_PREFIX + key, 1);
        redisTemplate.expire(JHJ_REDIS_KEY_PREFIX + key, expire, TimeUnit.SECONDS);
        return num;
    }
    
    @Override
    public Object hget(String domain, Object key){
        return redisTemplate.opsForHash().get(domain, key);
    }

    @Override
    public void hset(String domain, Object key, Object value, int expire){
        redisTemplate.opsForHash().put(domain, key, value);
        redisTemplate.expire(JHJ_REDIS_KEY_PREFIX + key, expire, TimeUnit.SECONDS);
    }
}
